#include "tinyxml2.h"
#include <iostream>

int main(){
	namespace xml = tinyxml2;

	xml::XMLDocument doc;

	xml::XMLElement& vtk = *( doc.NewElement("VTKFile") );
	doc.InsertFirstChild(&vtk);
	vtk.SetAttribute( "type", "ImageData" );
	vtk.SetAttribute( "version", "0.1" );
	vtk.SetAttribute( "byte_order", "LittleEndian" );

	xml::XMLElement& data = *( vtk.InsertNewChildElement( "ImageData" ) );
	data.SetAttribute( "WholeExtent", "0 3 0 3 0 0" );
	data.SetAttribute( "Origin", "0 0 0" );
	data.SetAttribute( "Spacing", "0.5 0.5 0" );

	vtk.SetAttribute( "extra", "value" );

	xml::XMLPrinter streamer;
	doc.Print( &streamer );

	std::cout << "From XMLDocument:\n" << streamer.CStr() << "\n";

	xml::XMLPrinter printer;

	printer.OpenElement( "VTKFile" );
	printer.PushAttribute( "type", "ImageData" );
	printer.PushAttribute( "version", "0.1" );
	printer.PushAttribute( "byte_order", "LittleEndian" );

	printer.OpenElement( "ImageData" );
	printer.PushAttribute( "WholeExtent", "0 3 0 3 0 0" );
	printer.PushAttribute( "Origin", "0 0 0" );
	printer.PushAttribute( "Spacing", "0.5 0.5 0" );
	printer.CloseElement();

	printer.CloseElement();

	printer.OpenElement( "VTKFile" );
	printer.PushAttribute( "extra", "value" );
	printer.CloseElement();

	std::cout << "From printer directly:\n" << printer.CStr() << "\n";

	xml::XMLElement* patches { vtk.InsertNewChildElement("boundaryPatches") };

	xml::XMLElement* patch { patches->InsertNewChildElement("patch") };

	auto testName = [&](){
		const char* patchName { patch->Attribute("name") };

		if ( patchName ){
			std::cout << "Attribute \"name\" exists and ";
			if ( std::string_view{ patchName }.empty() ){
				std::cout << "is empty.\n";
			} else {
				std::cout << "holds value \"" << patchName << "\".\n";
			}
		}
		else
			std::cout << "Attribute \"name\" not found.\n";
	};

	testName(); // not found
	patch->SetAttribute("name", "");
	testName(); // exists, but empty
	patch->SetAttribute("name", "bottom");
	testName(); // exists and holds value "bottom"

	return 0;
}